<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="650px"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="类型">
        <el-radio-group
          @change="radioChange"
          :disabled="itemDisabled"
          v-model="type"
        >
          <el-radio :label="1">菜单</el-radio>
          <el-radio :label="2">按钮/功能</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="title" :label="labelTitleName">
        <el-input
          :placeholder="'请输入' + labelTitleName"
          maxlength="72"
          v-model="form.title"
        ></el-input>
      </el-form-item>
      <el-form-item
        :required="type === 2"
        prop="parentIds"
        :label="labelParentName"
      >
        <el-cascader
          :options="menuTree"
          :props="checkStrictly"
          v-model="form.parentIds"
          :placeholder="cascaderPlaceholder"
          clearable
          @clearable="clearCascader"
          @change="changeCascader"
          ref="menuTreeCascader"
        ></el-cascader>
      </el-form-item>
      <el-form-item
        v-if="type === 1"
        prop="url"
        label="菜单URL"
        :required="form.parentIds.length != 0"
      >
        <el-input
          placeholder="请输入菜单URL"
          maxlength="72"
          @input="urlInput"
          v-model="form.url"
        ></el-input>
      </el-form-item>
      <el-form-item prop="permission" label="授权标识">
        <el-input
          placeholder="请输入授权标识"
          maxlength="36"
          v-model="form.permission"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="type === 1" prop="order" label="排序">
        <el-input
          placeholder="请输入排序"
          @input="orderInput"
          maxlength="2"
          v-model="form.order"
        ></el-input>
      </el-form-item>

      <div class="dialog-btns">
        <el-button @click="saveMenu" type="primary">{{
          this.form.id ? "编辑" : "新增"
        }}</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
  
<script>
import { addMenu, getMenuTree, getMenus, updateMenu } from "@/api/sys/sys";
export default {
  name: 'MenuEdit',
  props: {
    formData: {
      type: Object,
    },
    title: {
      type: String,
    },
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const parentIdsRule = (rule, value, callback) => {
      if (this.type === 2 && (!value || value.length === 0)) {
        callback(new Error("请选择所属菜单"));
      } else {
        callback();
      }
    };

    const urlRule = (rule, value, callback) => {
      if (this.type === 1 && this.form.parentIds.length != 0 && !value) {
        callback(new Error("请输入菜单URL"));
      } else {
        callback();
      }
    };

    return {
      menuTree: [],
      tableData: [],
      form: {
        id: null,
        title: null,
        parentIds: [],
        url: null,
        order: null,
        permission: null,
      },
      type: 1,
      rules: {
        title: [
          {
            required: true,
            min: 2,
            max: 30,
            message: "菜单名称长度为2~12个字符",
            trigger: "change",
          },
        ],
        parentIds: [
          {
            validator: parentIdsRule,
            trigger: "change",
          },
        ],
        url: [
          {
            validator: urlRule,
            trigger: "change",
          },
        ],
        // permission: [
        //   {
        //     min: 3,
        //     max: 36,
        //     message: "请输入3~12位授权标识",
        //     trigger: "change",
        //   },
        // ],
        order: [
          {
            required: true,
            message: "请输入排序",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.form = JSON.parse(JSON.stringify(this.formData));
    if (this.form.id) {
      this.type = this.form.type;
    }
    this.getMenuTreeHandle();
  },
  methods: {
    radioChange(val) {
      this.type = val;
      this.resetForm();
      this.$refs.ruleForm.resetFields();
    },
    getMenuTreeHandle() {
      getMenuTree().then((data) => {
        this.menuTree = data.data;
        this.$forceUpdate();
      });
    },
    resetForm() {
      this.form = {
        title: null,
        parentIds: [],
        url: null,
        order: null,
        permission: null,
      };
    },
    saveMenu() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let postData = JSON.parse(JSON.stringify(this.form));
          postData.parentId = postData.parentIds?.pop();
          postData.type = this.type;
          if (!this.form.id) {
            // 新增
            delete postData.id;
            delete postData.parentIds;
            addMenu(postData).then((res) => {
              this.closeDialog("refresh");
            });
          } else {
            if (postData.id === postData.parentId) {
              this.$message.error("不能选择当前节点！");
              return;
            }
            updateMenu(postData).then((res) => {
              this.closeDialog("refresh");
            });
          }
        }
      });
    },
    getMenusHandle() {
      getMenus().then((res) => {
        this.tableData = res.data;
      });
    },
    closeDialog(type) {
      if (type === "refresh") {
        setTimeout(() => {
          this.form = {};
          this.$refs.ruleForm.resetFields();
          this.$emit("closeDialog", type === "refresh");
        }, 100);
      } else {
        this.form = {};
        this.$refs.ruleForm.resetFields();
        this.$emit("closeDialog", type === "refresh");
      }
    },
    clearCascader() {
      this.$set(this.form, "parentIds", []);
    },
    changeCascader(val) {
      this.$set(this.form, "parentIds", val);
      this.$refs.menuTreeCascader.dropDownVisible = false;
    },
    urlInput(val) {
      this.form.url = val.replace(/[^a-zA-Z0-9\/]/g, "");
    },
    orderInput(val) {
      this.form.order = val.replace(/\D/g, "");
    },
  },
  computed: {
    dialogTitle() {
      return (this.formData.id ? "编辑" : "新增") + this.title;
    },
    itemDisabled() {
      return Boolean(this.form.id);
    },
    labelTitleName() {
      return this.type === 1 ? "菜单名称" : "按钮/功能名称";
    },
    labelParentName() {
      return this.type === 1 ? "上级菜单" : "所属菜单";
    },
    cascaderPlaceholder() {
      let result = "";
      if (this.type === 1) {
        result = "请选择上级菜单";
      } else {
        result = "请选择所属菜单";
      }
      if (this.form.id) {
        result = "- - -";
      }
      return result;
    },
    checkStrictly() {
      return { checkStrictly: this.type === 1 };
    },
  },
};
</script>

<style>
.dialog-btns {
  text-align: center;
}
.operators {
  margin-bottom: 16px;
}
.el-cascader {
  width: 100%;
}
.dialog-btns {
  text-align: center;
}
</style>